package multiconnector;

import java.io.IOException;
import java.net.InetAddress;

import multiconnector.broadcast.Channel;
import multiconnector.broadcast.PingBroadcaster;
import multiconnector.broadcast.ReceiverSocket.PacketListener;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * service for broadcast handshake
 */
public class MulticastService extends Service {

	public static final int COMMUNITY_PORT = 1337;
	public static final String APPLICATION_TAG = "MultiConnector";
	public static final String LOG_TAG = MulticastService.class.getName();

	private Channel mBroadcaster;

	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * start service and fire up threads
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(LOG_TAG, "created service");

		try {
			mBroadcaster = new Channel(this, COMMUNITY_PORT, APPLICATION_TAG);
		} catch (IOException e) {
			Log.e(LOG_TAG, "unable to create chanel", e);
		}
		mBroadcaster.joinChannel("test", "myKey");
		mBroadcaster.start();
		mBroadcaster.setOnReceiveHandler(new PacketListener() {

			@Override
			public void onPacketReceive(InetAddress pFrom, int pPort,
										Intent pData, boolean pWasEncrypted) {
				if (pWasEncrypted)
					System.out.println("Encrypted packet received!");
				if (PingBroadcaster.isPing(pData)) {
					Log.d(LOG_TAG, "Ping received from " + pFrom.toString() + "!");
				}
			}
		});
		mBroadcaster.sendPing(3000);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mBroadcaster.stop();
	}

}
